﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HappyBa.Core.Data;
using HappyBa.Core.Interfaces;

namespace HappyBa.Core.Validators
{
    public class TasksAndUserStoriesShouldHaveId : IValidator
    {
        public IEnumerable<ValidationResult> Validate(ValidationContext context)
        {
            foreach (var project in context.Metrics.Projects)
            {
                var knownIds = new List<string>();
                foreach (var userStory in project.UserStories)
                {
                    var id = GetId(userStory);
                    if (string.IsNullOrEmpty(id))
                    {
                        yield return new ValidationResult(string.Format("[{0}] Each user story should start with id: [example]", userStory));
                    }
                    else
                    {
                        if (!knownIds.Contains(id))
                        {
                            if (knownIds.Any())
                            {
                                yield return new ValidationResult(string.Format("[{0}] Each user story should have  the same ids: [{1}]", userStory, id));
                            }
                            knownIds.Add(id);
                        }
                        foreach (var e in userStory.Tasks.Cast<UIEstimatableEntityBase>().Concat(userStory.Bugs))
                        {
                            var eId = GetId(e);
                            if (!string.Equals(id, eId))
                            {
                                yield return new ValidationResult(string.Format("[{0}] Each assigned entity should have the same id as user story: [{1}]", e, id));
                            }
                        }
                    }
                }
            }
        }

        private string GetId(UIEstimatableEntityBase entity)
        {
            var name = entity.Name;
            if(!name.StartsWith("[") || !name.Contains("]"))return string.Empty;
            return name.Substring(1, name.IndexOf(']') - 1);
        }
    }
}
